package com.salinity.kun.task;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.List;

import com.salinity.kun.helper.BaseHydrologyDataHelper;
import com.salinity.kun.helper.CalculationHelper;
import com.salinity.kun.helper.ConstantHelper;
import com.salinity.kun.helper.FourierSeriesHelper;
import com.salinity.kun.model.FourierSeriesInput;
import com.salinity.kun.model.StationDateData;

public class FourierTask implements ITask {

	private Double[] Ft;
	private double T, T1, W, DeltaT;

	@Override
	public boolean run() throws IOException, ParseException {

		int rawDeltaT = 60;
		// 获取输入
		Path inputPath = Paths.get("E:\\Kuner\\研究生\\论文相关\\data\\绿华山\\LvhuaShan.csv");
		Path outputPath = Paths.get("E:\\Kuner\\BYLW\\Jworkspace\\saltyCode\\test\\");
		List<StationDateData> tidesList = BaseHydrologyDataHelper.getTidesFromFile(inputPath, rawDeltaT, 72);

		FourierSeriesInput fsi = BaseHydrologyDataHelper.hydToFsi(tidesList, rawDeltaT);

		FourierSeriesHelper fsh = new FourierSeriesHelper(fsi);
		Ft = fsi.getF();
		T = fsi.getT();
		DeltaT = fsi.getDeltaT();
		for (int i = 0; i < fsi.getSeriesCount(); i++) {
			System.out.println(get_a(i) - fsh.get_a(i));
		}

		// System.out.println(fsh.get_b(0));
		// System.out.println(fsh.get_ftCal(0));
		
		String[] itemArray = ConstantHelper.getOutputItems();
		 CalculationHelper.writeToFile(fsi, itemArray, outputPath.resolve("fs3.csv"));

		return true;
	}

	public double get_a(int index) {
		double a_i = 0.0;
		double up, down;
		int len = Ft.length;

		W = 2 * Math.PI / T;
		T1 = T / 2f;
		double t0 = -T1;
		up = Ft[0] * Math.cos(index * W * t0);
		down = Ft[len - 1] * Math.cos(index * W * T1);
		a_i = 0.5 * (up + down) * DeltaT;
		for (int i = 1; i < len - 1; i++) {
			t0 = -T1 + i * DeltaT;
			a_i += Ft[i] * Math.cos(index * W * t0) * DeltaT;
		}
		return 2 * a_i / T;
	}

	public double get_b(int index) {
		double b_i = 0.0;
		double up, down;
		int len = Ft.length;
		W = 2 * Math.PI / T;
		T1 = T / 2f;
		double t0 = -T1;

		up = Ft[0] * Math.sin(index * W * t0);
		down = Ft[len - 1] * Math.sin(index * W * T1);
		b_i = 0.5 * (up + down) * DeltaT;
		for (int i = 1; i < len - 1; i++) {
			t0 = -T1 + i * DeltaT;
			b_i += Ft[i] * Math.sin(index * W * t0) * DeltaT;
		}
		System.out.println( 2 * b_i / T);
		return 2 * b_i / T;
	}

	public static void main(String[] args) {
		ITask fsTask = new FourierTask();
		try {
			fsTask.run();
		} catch (IOException | ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
